//
//  ShouYinTaiViewController.m
//  XDLookPic
//
//  Created by wanglong8889@126.com on 14-5-26.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "ShouYinTaiViewController.h"

//支付宝客户端头文件
#import "DataSigner.h"
#import "AlixPayResult.h"
#import "DataVerifier.h"
#import "AlixPayOrder.h"
#import "PartnerConfig.h"
#import "AlixLibService.h"
#import "PayByBagViewController.h"
//#import "orderListViewController.h"

@interface ShouYinTaiViewController ()

@end

@implementation ShouYinTaiViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"乐宠收银台";
    self.contentView.backgroundColor = RGBA(247, 244, 239, 1.0);
    if (IOS7) {
        self.navigationBarBg.image = [UIImage imageNamed:@"redIOS7"];
    }else{
        self.navigationBarBg.image = [UIImage imageNamed:@"redIOS6"];
    }
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"pd_25_bai"] forState:UIControlStateNormal];
    self.titleLabel.textColor = [UIColor whiteColor];
    [self initShouYinTaiView];
    
    if (!IS_NOT_EMPTY(self.goodsName)) {
        self.goodsName = @"乐宠";
    }
    sel = @selector(paymentResult:);
    
}



-(void)initShouYinTaiView{
     [XDTools addAlabelForAView:self.contentView withText:@"订单提交成功，请尽快支付!" frame:CGRectMake(78.0, 10.0, 200.0, 12.0) font:[UIFont systemFontOfSize:13.0] textColor:[UIColor grayColor]];
    
    UIImageView *ddbhView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 35, 320, 78)];
    ddbhView.image = [UIImage imageNamed:@"ddbh"];
    [self.contentView addSubview:ddbhView];
    
    [XDTools addAlabelForAView:ddbhView withText:[NSString stringWithFormat:@"订单编号: %@",self.orderId] frame:CGRectMake(15.0, 18.0, 284.0, 16.0) font:[UIFont systemFontOfSize:14.0] textColor:UIColorFromRGB(0X333333)];
    
    UILabel * paynumberLabel = [XDTools addAlabelForAView:ddbhView withText:[NSString stringWithFormat:@"应付金额: %@",self.totalMo] frame:CGRectMake(15.0, 46.0, 284.0, 16.0) font:[UIFont systemFontOfSize:14.0] textColor:UIColorFromRGB(0X333333)];
    
    paynumberLabel.attributedText = [XDTools getAcolorfulStringWithText1:@"应付金额:  " Color1:UIColorFromRGB(0X333333) Font1:[UIFont systemFontOfSize:15.0] Text2:self.totalMo Color2:UIColorFromRGB(0Xdc4e2a) Font2:[UIFont systemFontOfSize:15.0] AllText:paynumberLabel.text];
    
    
    //初始化支付方式
    UIImageView *zffsView = [[UIImageView alloc] initWithFrame:CGRectMake(0, ddbhView.frame.origin.y+ddbhView.frame.size.height+10, 320, 168)];
    zffsView.userInteractionEnabled = YES;
     zffsView.image = [[UIImage imageNamed:@"ddbh"]resizableImageWithCapInsets:UIEdgeInsetsMake(10, 20, 10, 20)];
    [self.contentView addSubview:zffsView];
    
    
    
    [XDTools addAlabelForAView:zffsView withText:@"支付方式:" frame:CGRectMake(15.0, 11.0, 284.0, 16.0) font:[UIFont systemFontOfSize:14.0] textColor:[UIColor blackColor]];
    
    UIImageView *firstLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 37, 320, 1/2.0)];
    firstLineView.image = [UIImage imageNamed:@"line640"];
    [zffsView addSubview:firstLineView];
    
    
   UILabel *kHLabel =  [XDTools addAlabelForAView:zffsView withText:@"支付宝客户端支付" frame:CGRectMake(15.0, 13.0+firstLineView.frame.origin.y+firstLineView.frame.size.height, 200.0, 16.0) font:[UIFont systemFontOfSize:13.0] textColor:[UIColor blackColor]];
    
    [XDTools addAlabelForAView:zffsView withText:@"建议已安装支付宝客户端的用户使用" frame:CGRectMake(15.0, kHLabel.frame.origin.y+kHLabel.frame.size.height+5, 284.0, 16.0) font:[UIFont systemFontOfSize:10.0] textColor:[UIColor grayColor]];
    
    
    PayButton = [XDTools getAButtonWithFrame:CGRectMake(self.view.frame.size.width-15-22, firstLineView.frame.origin.y+firstLineView.frame.size.height+20, 22,22.0) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:nil nbgImage:nil hbgImage:nil action:nil target:self buttonTpye:UIButtonTypeCustom];
    [PayButton setBackgroundImage:[UIImage imageNamed:@"uns_quan"]  forState:UIControlStateNormal];
    [PayButton setBackgroundImage:[UIImage imageNamed:@"squan"]  forState:UIControlStateSelected];
    PayButton.selected = YES;
    [zffsView addSubview:PayButton];
    
    UIButton *payAliphaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    payAliphaBtn.frame = CGRectMake(firstLineView.frame.origin.x, firstLineView.frame.origin.y+firstLineView.frame.size.height, firstLineView.frame.size.width, 65);
    payAliphaBtn.tag = 1800;
    [payAliphaBtn addTarget:self action:@selector(payTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [zffsView addSubview:payAliphaBtn];
    
    
    
    UIImageView *secondLineView = [[UIImageView alloc] initWithFrame:CGRectMake(15,firstLineView.frame.origin.y+firstLineView.frame.size.height+65, 305, 1/2.0)];
    secondLineView.image = [UIImage imageNamed:@"line610"];
    [zffsView addSubview:secondLineView];
    
    
    
    //web
    UILabel *webLabel =  [XDTools addAlabelForAView:zffsView withText:@"支付宝网页支付" frame:CGRectMake(15.0, 13.0+secondLineView.frame.origin.y+secondLineView.frame.size.height, 200.0, 16.0) font:[UIFont systemFontOfSize:13.0] textColor:[UIColor blackColor]];
    
    [XDTools addAlabelForAView:zffsView withText:@"建议未安装支付宝客户端的用户使用" frame:CGRectMake(15.0, webLabel.frame.origin.y+webLabel.frame.size.height+5, 284.0, 16.0) font:[UIFont systemFontOfSize:10.0] textColor:[UIColor grayColor]];
    
    
    webButton = [XDTools getAButtonWithFrame:CGRectMake(self.view.frame.size.width-15-22, secondLineView.frame.origin.y+secondLineView.frame.size.height+20, 22,22.0) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:nil nbgImage:nil hbgImage:nil action:nil target:self buttonTpye:UIButtonTypeCustom];
    [webButton setBackgroundImage:[UIImage imageNamed:@"uns_quan"]  forState:UIControlStateNormal];
    [webButton setBackgroundImage:[UIImage imageNamed:@"squan"]  forState:UIControlStateSelected];
    [zffsView addSubview:webButton];
    
    UIButton *webAliphaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    webAliphaBtn.frame = CGRectMake(secondLineView.frame.origin.x, secondLineView.frame.origin.y+secondLineView.frame.size.height, secondLineView.frame.size.width, 65);
    webAliphaBtn.tag = 1900;
    [webAliphaBtn addTarget:self action:@selector(payTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [zffsView addSubview:webAliphaBtn];
    
    
    
    
    UIButton * goPayButton = [XDTools getAButtonWithFrame:CGRectMake(70, zffsView.frame.origin.y+zffsView.frame.size.height+36, 180,34.0) nomalTitle:@"去支付" hlTitle:@"去支付" titleColor:[UIColor whiteColor] bgColor:nil nbgImage:@"gotopay" hbgImage:@"gotopay" action:@selector(goToPayAction) target:self buttonTpye:UIButtonTypeCustom];
    goPayButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
    
    [self.contentView addSubview:goPayButton];
   
}


//选择支付方式
-(void)payTypeAction:(UIButton *)btn{
    if (btn.tag == 1800) {
        if (!PayButton.selected) {
            PayButton.selected = YES;
            webButton.selected = NO;
            
        }
    }else{
        if (!webButton.selected) {
            webButton.selected = YES;
            PayButton.selected = NO;
    }
}
}
//去支付
-(void)goToPayAction{
    
    [self confirmDingDanDatas];
    
}



//通过web支付
-(void)payByWeb{
    NSString *uuid =[[[NSUserDefaults standardUserDefaults]objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    NSString *str0 = [[NSString stringWithFormat:@"%@?WIDout_trade_no=%@&WIDsubject=%@&WIDtotal_fee=%.2f&WIDis_buy=%@&uuid=%@",PAY_IP,_orderId,self.goodsName,[orderAmount floatValue],@"1",uuid]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *payURL = [str0 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
   
   
    //            [[NetworkModule sharedNetworkModule] postData:nil tag:kSXTagALiPay owner:self url:payURL];
    NSURL *malongUrl = [NSURL URLWithString:payURL];
    
    
    PayByBagViewController *payVC = [[PayByBagViewController alloc] init];
    payVC.webUrl = malongUrl;
    [self.navigationController pushViewController:payVC animated:YES];
    DDLOG_CURRENT_METHOD;
    
}
//通过客户端
-(void)payByKeHuDuan{
    
//   BOOL yy =  [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"com.alipay.app"]];
    
    NSString *appScheme = @"com.xindao.lechong";
    NSString* orderInfo = [self getOrderInfo];
    NSString* signedStr = [self doRsa:orderInfo];
    
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                             orderInfo, signedStr, @"RSA"];
    NSLog(@"orderString:%@",orderString);
    
    
    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:sel target:self];
    
    
    
}

//支付宝回调
-(void)paymentResultDelegate:(NSString *)result{
    
}

-(NSString*)getOrderInfo
{
    //拼接商品信息
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.partner = PartnerID;
    order.seller = SellerID;
    
    //    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    //	order.productName = product.subject; //商品标题
    //	order.productDescription = product.body; //商品描述
    //	order.amount = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
    //	order.notifyURL =  @"http%3A%2F%2Fwwww.xxx.com"; //回调URL
	
    
    order.productName = self.goodsName;
    order.tradeNO = self.orderId;  //订单ID（由商家自行制定）
    order.productDescription = @"这里是商品描述";
    order.amount = orderAmount; //商品价格
    order.notifyURL = @"http://ts.leepet.com/plugins/API.v1.0/?&a=order&m=notify&code=alipay"; //回调URL
    
	return [order description];
}

-(NSString*)doRsa:(NSString*)orderInfo
{
    id<DataSigner> signer;
    signer = CreateRSADataSigner(PartnerPrivKey);
    NSString *signedString = [signer signString:orderInfo];
    return signedString;
}



//wap回调函数
-(void)paymentResult:(NSString *)resultd
{
    //结果处理
#if ! __has_feature(objc_arc)
    AlixPayResult* result = [[[AlixPayResult alloc] initWithString:resultd] autorelease];
#else
    AlixPayResult* result = [[AlixPayResult alloc] initWithString:resultd];
#endif
	if (result)
    {
		
		if (result.statusCode == 9000)
        {
			/*
			 *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
			 */
            
            //交易成功
            NSString* key = AlipayPubKey;//签约帐户后获取到的支付宝公钥
			id<DataVerifier> verifier;
            verifier = CreateRSADataVerifier(key);
            
			if ([verifier verifyString:result.resultString withSign:result.signString])
            {
                //验证签名成功，交易结果无篡改
			}
        }
        else
        {
            //交易失败
        }
    }
    else
    {
        //失败
    }
    
}
//跳到订单页面
-(void)completeShop{
//    orderListViewController * ovc = [[orderListViewController alloc] init];
//    ovc.type = @"0";
//    [self.navigationController pushViewController:ovc animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)confirmDingDanDatas{
    
    
    
    if ([XDTools NetworkReachable])
    {
        NSDictionary * dic = @{@"order_sn":self.orderId,
                               
                               };
        
        
        ASIHTTPRequest *request = [XDTools postECShopRequestWithDict:dic API:API_CHECKORDER sign:@"1"];
        __weak ASIHTTPRequest * mrequest = request;
        [request setCompletionBlock:^{
            
            [XDTools hideProgress:self.view];
            
            NSDictionary *tempDic = [XDTools  JSonFromString:[mrequest responseString]];
            DDLOG(@"temdic = %@",tempDic);
            if ([[tempDic objectForKey:@"status"] intValue] == 1)
            {
                orderAmount = [[tempDic objectForKey:@"data"] objectForKey:@"order_amount"];
                
                if (PayButton.selected) {
                    [self payByKeHuDuan];
                }else{
                    [self payByWeb];
                }
                
            }else{
                [XDTools showTips:[tempDic objectForKey:@"msg"] toView:self.view];
            }
            
            
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.view];
            NSError *error = [mrequest error];
            DDLOG_CURRENT_METHOD;
            DDLOG(@"error=%@",error);
            if (mrequest.error.code == 2) {
                [XDTools showTips:@"网络请求超时" toView:self.view];
            }
        }];
        [XDTools showProgress:self.view showText:@"正在跳入支付宝..."];
        [request startAsynchronous];
        
    }
    else
    {
        [XDTools showTips:brokenNetwork toView:self.view];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
